<template>
  <!-- 广告创意  删除标签未完成 -->
  <div>
    <div class="batch-block">
      <div class="batch-form-model">
        <a-form-model
          ref="ruleForms"
          :model="creativeForm"
          :rules="rules"
          label_align='right'
          :label-col="{ span: 3 }"
          :wrapper-col="{ span: 20 }"
        >
          <!-- 投放范围 -->
          <div class="formModel">
            <div class="formModel-title">设置投放位置</div>
            <a-form-model-item label="广告位置">
              <a-radio-group
                v-model="creativeForm.smartType"
                button-style="solid"
                :disabled="is_union"
              >
                <a-radio-button disabled value="smart"> 优选广告位 </a-radio-button>
                <a-radio-button value="media"> 按媒体指定位置 </a-radio-button>
                <a-radio-button value="scene"> 按场景指定位置 </a-radio-button>
              </a-radio-group>
              <!-- 广告(媒体) -->
              <a-checkbox-group
                v-if="creativeForm.smartType === 'media' "
                style="display: block;"
                v-model="creativeForm.inventory_type"
                button-style="solid"
                :disabled="is_union"
              >
                <a-checkbox
                  v-for="(item,index) in this.$global.inventoryType"
                  :key="index"
                  :value="item.value"
                >
                  {{ item.label }}
                </a-checkbox>
              </a-checkbox-group>
              <!-- 场景 -->
              <a-radio-group
                v-if="creativeForm.smartType === 'scene' "
                style="display: block;" is_scene
                v-model="creativeForm.scene_inventory"
              >
                <a-radio
                  v-for="(item,index) in this.$global.sceneInventory"
                  :key="index"
                  :value="item.value"
                >
                  {{ item.label }}
                </a-radio>
              </a-radio-group>
            </a-form-model-item>
          </div>
          <!-- 创意 -->
          <div class="formModel" >
            <div class="formModel-title">制作创意</div>

            <a-form-model-item label="创意方式">
              <material ref="creativeMaterial" ></material>
            </a-form-model-item>
            
            <a-form-model-item label="推广卡片" v-show="is_promotion_card">
              <promotion-card ref="promotionCard" v-model="creativeForm.promotion_card" ></promotion-card>
            </a-form-model-item>
            <!-- DOWNLOAD_URL 暂时无用 -->
            <a-form-model-item v-if="is_downloadType === 'DOWNLOAD_URL' " label="应用名" prop="app_name">
              <a-input v-model="creativeForm.app_name"></a-input>
            </a-form-model-item>
            <a-form-model-item v-else-if="is_downloadType === 'EXTERNAL_URL'" label="来源" prop="source">
              <a-input v-model="creativeForm.source"></a-input>
            </a-form-model-item>

            <a-form-model-item label="副标题">
              <a-input v-model="creativeForm.advanced_creative_title"></a-input>
            </a-form-model-item>
            <a-form-model-item label="最优创意衍生计划">
              <a-radio-group
                v-model="creativeForm.generate_derived_ad"
                button-style="solid"
              >
                <a-radio-button :value="0"> 关闭 </a-radio-button>
                <a-radio-button :value="1"> 开启 </a-radio-button>
              </a-radio-group>
            </a-form-model-item>
            <a-form-model-item label="广告评论">
              <a-radio-group
                  v-model="creativeForm.is_comment_disable"
                  button-style="solid"
                >
                  <a-radio-button :value="1"> 关闭 </a-radio-button>
                  <a-radio-button :value="0"> 开启 </a-radio-button>
                </a-radio-group>
            </a-form-model-item>
            <a-form-model-item label="创意展现">
              <a-radio-group
                  v-model="creativeForm.creative_display_mode"
                  button-style="solid"
                >
                  <a-radio-button 
                    v-for="(item,index) in this.$global.creativeDisplayMode"
                    :key="index"
                    :value="item.value"
                  > {{ item.label }} </a-radio-button>
                </a-radio-group>
            </a-form-model-item>
          </div>
          <!-- 创意标签 -->
          <div class="formModel">
            <div class="formModel-title">设置创意标签</div>
            <a-form-model-item label="创意分类">
              <a-cascader
                width="300px"
                v-model="creativeForm.third_industry_id"
                :fieldNames="{ label:'name',value:'id',children: 'children' }"
                placeholder="请选择创意分类"
                :allowClear="false"
                :options="industryOptions"
              />
            </a-form-model-item>

            <a-form-model-item label="创意标签" prop="" >
              <div class="tags-input">
                <!-- <a-input-search placeholder="input search text" enter-button @search="addTags" /> -->
                <a-input v-model="tags" style="width:400px;margin-right:20px;" @pressEnter="addTags" placeholder="最多20个标签，每个不超过十个字，可用空格或者'，'分隔" />
                <a-button type="primary" @click="addTags"> 添加 </a-button>
              </div>
              <div class="tags" v-if="creativeForm.ad_keywords.length !== 0">
                <template v-for="tag in creativeForm.ad_keywords">
                  <a-tooltip v-if="tag.length > 20" :key="tag" :title="tag">
                    <a-tag :key="tag" closable @close="() => closeTags(tag)">
                      {{ tag }}
                    </a-tag>
                  </a-tooltip>
                  <a-tag :key="tag" closable @close="() => closeTags(tag)">
                    {{ tag }}
                  </a-tag>
                </template>
              </div>
            </a-form-model-item>
          </div>
        </a-form-model>
      </div>
    </div>

    <div class="next">
      <a-button type="primary" @click="next">
        下一步
      </a-button>
    </div>
   
  </div>
</template>

<script>
import { queryIndustry } from "@/api/queryTool";

export default {
  components:{ 
    'Material':()=>import('../components/creative/material'),
    'promotionCard':()=>import('../components/creative/promotionCard')
  },
  data(){
    return {
      is_downloadType: 'EXTERNAL_URL',
      industryOptions:[], // 行业数据
      tags:'',  // 标签 input
      is_union:false, // 当前投放范围是否是穿山甲
      creativeForm:{
        smartType:'media', // 判断广告类型（不需要传入参数类型，只做判断）
        smart_inventory:1, // 优选广告位 与 scene_inventory 不能同时传。
        scene_inventory:'FEED_SCENE',  // 场景广告位   忽略 inventory_type 
        inventory_type:['INVENTORY_FEED','INVENTORY_AWEME_FEED'],  // 媒体
        advanced_creative_title:'', // 副标题
        generate_derived_ad:0,  // 最优创意衍生计划
        is_comment_disable:1, // 广告评论
        creative_display_mode:'CREATIVE_DISPLAY_MODE_CTR',  // 创意展现方式
        third_industry_id:['1922', '192204', '19220401'], //行业 id
        ad_keywords:[], //标签

        promotion_card:{
          product_image_id:'', // 卡片主图 id
          product_description:'', // 卡片标题
          enable_store_pack:false, // 门店 
          enable_personal_action:true,  //智能优选
          call_to_action:'阅读全文', // 行动号召
          product_selling_points:['商家倾情推荐1']   //商品卖点
        }  // 推广卡片
      },
      rules:{
        app_name: [{ required: true,message:'请输入应用名', trigger: 'change' }],
        source: [{ required: true,message:'请输入来源', trigger: 'change' }],
        ad_keywords: [{ required: true,message:'请添加创意标签', trigger: 'change' }],
      },
    }
  },
  watch:{
    // 判断下载方式 落地页(来源)/下载链接(应用名)    // 无用
    '$store.state.batchCreated.ad':function (ad) {
      this.is_downloadType = ad.download_type
      if( ad.delivery_range === 'UNION'){  // 如果投放范围是穿山甲，将广告位置固定穿山甲并禁止选择广告位置
        this.is_union = true
        this.creativeForm.inventory_type = [ 'INVENTORY_UNION_SLOT' ]
      }else {
        this.is_union = false
      }
    },
  },
  computed:{
    is_promotion_card(){
      if( this.creativeForm.smartType === 'media' && this.creativeForm.inventory_type.indexOf('INVENTORY_AWEME_FEED') === -1 ) return false
      if( this.creativeForm.smartType === 'scene' ) return false
      return true
    }
  },
  created(){
    if( Object.keys(this.$route.query).length !== 0 ){
      this.creativeForm = Object.assign( this.creativeForm,JSON.parse(this.$route.query.data).creativeForm ) 
    }
    this.getIndustry()
  },
  methods:{
    getIndustry(){
      queryIndustry().then((res)=>{
        this.industryOptions = res.data
      })
    },
    // 添加标签
    addTags(){
      if( this.tags.trim() !== '' ){
        let arr = this.tags.replace(/,/g,' ').replace(/，/g,' ').trim().split(/\s+/)  //空格 , ，分隔
        if(this.tags !== '' && this.creativeForm.ad_keywords.length <= 20 && arr.length <= 20){
          arr.forEach(ele => {
            if( this.creativeForm.ad_keywords.indexOf( ele ) === -1 ) this.creativeForm.ad_keywords.push(ele)
          });
          this.tags = ''
        }
      }else this.$Tip('请正确输入创意标签')
    },
    // 删除标签（未完成）
    closeTags(removedTag){
      const tags = this.creativeForm.ad_keywords.filter(tag => tag !== removedTag);
      this.creativeForm.ad_keywords = tags;
    },
    // 下一步
    async next(){
      let is_creative = await this.$refs.creativeMaterial.nextItem()  //判断创意素材是否为真

      let promotionCardForm = ''
      if( this.is_promotion_card && is_creative ){
        promotionCardForm = await this.$refs.promotionCard.rulesInfo()  // 判断推广卡片
      }
      console.info(this.$store.state.batchCreated.creativeGroups,'creativeGroups11111')
      if(is_creative){
        this.$refs['ruleForms'].validate(valid => {
          if (valid) {
            
            let creatives_copy = this.$deepCopy(this.creativeForm)
            if( this.is_promotion_card ){
              if( promotionCardForm ){
                // 如果卡片为真,判断是否有视频素材
                let creatives = this.$store.state.batchCreated.creativeGroups
                let is_video = false
                for (const creative of creatives) {
                  for (const list of creative.creativeList) {
                    if( list.materialItem.material_type === 'video' ) is_video = true
                  }
                }
                if( !is_video ) return this.$Tip('推广卡片需要包含视频创意，请补充视频素材')
              }else {
                return false
              }
            }else {
              delete creatives_copy.promotion_card
            }

            if( creatives_copy.ad_keywords.length === 0 ) return alert('请添加创意标签') 

            // 判断广告投放位置
            if( creatives_copy.smartType === 'media' ){
              delete creatives_copy.smart_inventory
              delete creatives_copy.scene_inventory
            }else if( creatives_copy.smartType === 'scene' ){
              delete creatives_copy.inventory_type
              delete creatives_copy.smart_inventory
            }
            creatives_copy.third_industry_id = this.creativeForm.third_industry_id[this.creativeForm.third_industry_id.length-1]  // 获取行业标签(最后的一个id)

            localStorage.setItem('creative',JSON.stringify(creatives_copy))
            this.$store.commit('SET_CREATIVE',creatives_copy)
            this.$store.commit('SET_CREATIVE_FORM',this.creativeForm)  // 回显数据
            this.$emit('nexts')
          } else {
            return false;
          }
        });
      }

    }
  }
}
</script>

<style lang="less" scoped>
  .ant-input{
    width: 350px;
  }
  // 标签
  .tags-input{
    display: block;
  }
  .tags{
    width: 400px;
    border: 1px solid #F0F2F5;
  }
</style>